# @Time    :2025/4/16 23:47

# 实现一个简单的文件拷贝函数，支持大文件分块拷贝。

def copy_file(source, destination, buffer_size=1024):
    with open(source, 'rb') as src, open(destination, 'wb') as dst:
        while True:
            data = src.read(buffer_size)
            if not data:
                break
            dst.write(data)


# 如果需要复制大文件并显示进度，可以在循环中添加进度条或日志输出
import os


def copy_file_with_progress(source, destination, buffer_size=1024):
    total_size = os.path.getsize(source)  # 获取源文件大小
    copied_size = 0
    with open(source, 'rb') as src, open(destination, 'wb') as dst:
        while True:
            data = src.read(buffer_size)
            if not data:
                break
            dst.write(data)
            copied_size += len(data)
            print(f"Copied {copied_size}/{total_size} bytes ({copied_size / total_size * 100:.2f}%)")


# 可以添加异常处理，确保在发生错误时能够捕获并提示用户：

def copy_file_safe(source, destination, buffer_size=1024):
    try:
        with open(source, 'rb') as src, open(destination, 'wb') as dst:
            while True:
                data = src.read(buffer_size)
                if not data:
                    break
                dst.write(data)
        print("File copied successfully.")
    except FileNotFoundError:
        print(f"Error: Source file '{source}' not found.")
    except PermissionError:
        print("Error: Permission denied.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


# ---------------------------------------------------------------------------------

# 创建一个银行账户类(BankAccount)，包含存款、取款和查询余额功能，并实现简单的异常处理
class BankAccount:
    def __init__(self, initial_balance=0):
        self.balance = initial_balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("存款金额必须大于0")
        self.balance += amount

    def withdraw(self, amount):
        if amount <= 0:
            raise ValueError("取款金额必须大于0")
        if amount > self.balance:
            raise ValueError("余额不足")
        self.balance -= amount

    def get_balance(self):
        return self.balance



#---------------------------------------------------------------------------------

# 编写一个函数，统计一个目录及其子目录下所有.py文件的行数。
# os.path.join(*paths)	拼接多个路径，自动处理路径分隔符

import os


def count_py_lines(directory):
    total_lines = 0
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.py'):
                with open(os.path.join(root, file), 'r', encoding='utf-8') as f:
                    total_lines += len(f.readlines())
    return total_lines
